<?php

class Core_Model_DbTable_CandidateInfo extends YouNet_Db_Table implements Core_Model_IEntryFields
{
	const TABLE_NAME = 'candidate_info';
	protected $_name = self::TABLE_NAME;
	protected $_primary = array('id_entry_field', 'id_user');
	protected $_rowClass = 'Core_Model_CandidateInfo';
	private static $_instance;

	/**
	 * @author hungnq
	 * @return Core_Model_DbTable_CandidateInfo
	 */
	public static function getInstance()
	{
		if(is_null(self::$_instance))
		{
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	public function getDisplayedCandidateInfo($id_user, $id_contest)
	{
		$query = $this->_getCandidateInfo($id_user, $id_contest);
		$query->where('ef.is_displayed=?', 1);
		return $this->fetchAll($query);
	}

	public function getCandidateInfo($id_user, $id_contest)
	{
		$query = $this->_getCandidateInfo($id_user, $id_contest);
		return $this->fetchAll($query);
	}

	private function _getCandidateInfo($id_user, $id_contest)
	{
		$query = $this->select()
				->setIntegrityCheck(false)
				->from(array('ci' => self::TABLE_NAME), array('ci.value', 'ci.id_entry_field'))
				->joinLeft(array('ef' => 'entry_fields'), 'ef.id = ci.id_entry_field', array('ef.label','ef.type'))
				->where('ci.id_user=?', $id_user)
				->where('ef.id_contest=?', $id_contest)
				->order('ef.type asc');
		return $query;
	}

	public function getCandidateName($id_user, $id_contest)
	{
		$result			= $this->getCandidateInfo($id_user, $id_contest);
		$fullname		= '';
		foreach($result as $row)
		{
			if($row->type == self::INDEX_FULL_NAME)
			{
				$fullname = $row->value;
			}
		}
		return trim($fullname);
	}

	public function getDbRow($id_entry_field, $id_user)
	{
		$row = $this->findOne($id_entry_field, $id_user);

		if(empty($row))
		{
			$row = $this->createRow();
		}

		return $row;
	}

	public function insertFromParams($params, $id_user)
	{
		foreach($params as $key => $value)
		{
			$candidateInfo					= $this->getDbRow($key, $id_user);
			$candidateInfo->id_entry_field	= $key;
			$candidateInfo->id_user			= $id_user;
			$candidateInfo->value			= $value;
			$candidateInfo->save();
		}
	}

}
